<?php

namespace PhpSeverless;

class CgiResponseParser
{
    public $raw;

    public $rawHeader;

    public $headers;

    public $body;

    public $statusCode = 200;

    public function __construct($raw)
    {
        $this->raw = $raw;
        $this->parse();
    }

    public function parse()
    {
        $raw = $this->raw;
        $split = strpos($raw, "\n\r");
        $this->rawHeader = substr($raw, 0, $split);
        $this->body = substr($raw, $split + 3);
    }

    public function getStatusCode()
    {
        if (empty($this->headers)) {
            $this->getHeaders();
        }
        return $this->statusCode;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function getHeaders()
    {
        $rawHeader = $this->rawHeader;

        $headers = [];
        $lines = explode(PHP_EOL, $rawHeader);
        foreach ($lines as $k => $line) {
            if (preg_match('#^([^\:]+):(.*)$#', $line, $matches)) {
                $key = trim($matches[1]);
                $value = trim($matches[2]);

                // 状态码
                if ($key == 'Status' && $k == 0) {
                    $this->statusCode = (int) $value;
                    continue;
                }

                if (array_key_exists($key, $headers)) {
                    $headers[$key][] = $value;
                } else if (in_array(strtoupper($key), array('CONTENT-TYPE'))) {
                    // 云函数API网关的CONTENT-TYPE只支持字符串，不支持传递数组
                    $headers[$key] = $value;
                } else {
                    $headers[$key] = array($value);
                }
                continue;
            }
        }
        $this->headers = $headers;
        return $this->headers;
    }
}
